#include "VideoStreamer\VideoStreamerFactory.h"
#include <highgui.h>
#include <boost/thread.hpp>
#include <iostream>

bool running = true;
void readKey(void)
{
	std::cout << "Press 'c'+'Enter' to exit..." << std::endl;
	char c;
	do std::cin >> c;
	while (c != 'c');
	running = false;
}

void main_highgui(void)
{
	// Configuration parameters
	const char *uri = "rtp://127.0.0.1:1234?localport=9001";
	int bitRate = 1e6; // 1e6
	int frameRate = 25;

	// Open camera frame grabber and video streamer
	CvCapture *capture = cvCaptureFromCAM(0);
	Sleep((DWORD)1e3); // The camera is slow opening. Lets wait for it.

	CvVideoWriter *writer = cvCreateStreamingVideoWriter(
		uri, 
		CV_FOURCC('M','P','G','2'), 
		frameRate, 
		cvGetSize(cvQueryFrame(capture)),
		1);

	// Send video form the camera through the VideoStreamer element.
	boost::thread thrd(&readKey);
	IplImage *img;
	ULONG startTime = GetTickCount();
	ULONG framesSent = 0;

	while(running)
	{
		ULONG timeElapsed = GetTickCount() - startTime;
		ULONG targetFramesSent = (ULONG)(frameRate*timeElapsed)/1000.0;
		if (framesSent < targetFramesSent) 
		{
			img = cvQueryFrame(capture);
			cvFlip(img, img, 0);
			cvWriteStreamingFrame(writer, img); // genera un memory leak
			framesSent++;
		}
	}

	// Release resources. Close framme graber and video streamer.
	cvReleaseCapture(&capture);
	cvReleaseVideoWriter(&writer);
}


void main(void)
{
	// Configuration parameters
	//std::string uri = "test.flv";
	std::string uri = "rtp://227.0.0.1:1234?multicast=1";
	//std::string uri = "rtp://127.0.0.1:1234?localport=9001";

	// Formats: http://lists.mplayerhq.hu/pipermail/ffmpeg-user/2006-March/002425.html
	// application/x-shockwave-flash (swf)
	// video/x-flv (flv)
	// video/x-mjpeg (mjpeg)
	// video/x-msvideo (avi)
	// video/mpeg (mpeg)
	// (m4v) (mpegts)
	// (ogg) (h264)

	std::string format = "mpegts";
	int bitRate = 1e6;
	int frameRate = 25;
	int gopSize = 1;
	int bFrames = 0;
	int bufferSize = 2e5;

	// Open camera frame grabber and video streamer
	CvCapture *capture = cvCaptureFromCAM(0);
	Sleep((DWORD)1e3); // The camera is slow opening. Lets wait for it.
	IVideoStreamer *vs = VideoStreamerFactory::CreateInstance(
		uri.c_str(), format.c_str(), 
		cvGetSize(cvQueryFrame(capture)),bitRate, frameRate, gopSize, bFrames, bufferSize);
	vs->OpenVideo();

	// Send video form the camera through the VideoStreamer element.
	boost::thread thrd(&readKey);
	IplImage *img;
	while(running)
	{
		img = cvQueryFrame(capture);
		cvFlip(img, img, 0);
		vs->Update(img);

		Sleep((DWORD)1000/frameRate);
	}

	// Release resources. Close framme graber and video streamer.
	vs->CloseVideo();
	delete vs;
	cvReleaseCapture(&capture);
}
